package com.example.qqfake;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class EditProfileActivity extends AppCompatActivity {
    private final String serverAddress = "192.168.104.215";
    private final int serverPort = 50000;

    public Socket socket;
    private PrintWriter out;
    private BufferedReader in;


    private Toolbar toolbar;

    private Button exit_button;

    private TextView igNameEdit;

    private TextView igGenderRr;

    private EditText igRegionn;

    private TextView brithday;
    private TextView ig_id;

    public SharedPreferences.Editor editor;

    private Button tuichu;
    private static final int REQUEST_CODE_SELECT_IMAGE = 1;
    private Uri selectedImageUri;
    private String key;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);
        // 初始化视图
        initViews();
        // 设置Toolbar
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);



        // 获取SharedPreferences实例，文件名为"myPreferences"，与MainActivity中使用的文件名相同
        SharedPreferences sharedPreferences = getSharedPreferences("myPreferences", Context.MODE_PRIVATE);

        // 获取SharedPreferences.Editor对象来编辑数据
        editor = sharedPreferences.edit();
        // 读取数据，键为"User_id"
        // 获取传递过来的username
        String user_id = sharedPreferences.getString("User_id","hhh");
        ig_id.setText(user_id);

        // 设置保存按钮点击事件
        exit_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = igNameEdit.getText().toString();
                String gender = igGenderRr.getText().toString();
                String address = igRegionn.getText().toString();
                String birthday = brithday.getText().toString();
                String info = user_id+" "+name+" "+gender+" "+address+" "+birthday;
                //发送保存请求：
                //子线程发送消息
                Date now = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedString = formatter.format(now);
                String message = "4,"+user_id+","+formattedString+","+info+","+user_id;

                Thread thread = new Thread(new Worker(message));
                thread.start();

            }
        });
        tuichu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(EditProfileActivity.this,LoginActivity.class);
                startActivity(intent);
            }
        });

        //子线程开启socket发送连接请求，不停监听信息
        new Thread(()->{
            try {

                socket= new Socket(serverAddress, serverPort);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out= new PrintWriter(socket.getOutputStream(), true);



                //发送请求当前用户信息
                Date now = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedString = formatter.format(now);
                String message = "9,"+user_id+","+formattedString+","+user_id+","+user_id;

                out.println(message);

                // 启动读取消息的线程
                new Thread(this::readMessages).start();
                /*
                 * 由EditProfileActivity发送的消息：
                 *
                 * 1.当前用户信息，返回当前用户所有的信息：姓名，性别，生日，地址
                 *              先在tb_user表中查找，是否有该用户，若没有先插入，插入成功返回insert_true
                 *              若存在，读取姓名，性别，生日，地址等信息,格式（姓名+" "+性别+" "+地址+" "+生日）
                 *
                 *
                 * 2.修改用户信息，用户修改个人信息后，点击保存按钮，向服务器发送请求，服务器对数据库进行更新
                 *              若成功返回 modify_success
                 *              若失败返回 false9
                 *
                 *
                 * */

            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }).start();





    }

    private void initViews() {
        toolbar = findViewById(R.id.tool_bar);

        exit_button= findViewById(R.id.exit_button);

        ig_id = findViewById(R.id.ig_id);

        igNameEdit = findViewById(R.id.ig_nameedit);

        igGenderRr = findViewById(R.id.ig_genderrr);

        igRegionn = findViewById(R.id.ig_regionn);

        brithday = findViewById(R.id.brithday);
        tuichu = findViewById(R.id.tuichu);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SELECT_IMAGE && resultCode == RESULT_OK && data != null) {
            selectedImageUri = data.getData();
            ImageView imageView = findViewById(R.id.ri_portrait);
            imageView.setImageURI(selectedImageUri);
        }
    }

    public void selectImage(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE);
    }




    private void readMessages() {

        try {

            String message;
            while ((message = in.readLine()) != null) {
                if(message.equals("insert_true")){
                    Log.v("msg","modify_answer0");
                    break;

                }
                else if(message.equals("modify_success")){
                    Log.v("msg","modify_answer1");
                    //弹窗提示，修改保存成功

                    if(!isFinishing()){
                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
                            @Override
                            public void run() {
                                Log.v("msg","modify_answer2");
                                //更新UI界面
                                Toast.makeText(EditProfileActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(EditProfileActivity.this, MainActivity.class);
                                // 保存数据，键为"exampleKey"，值为"exampleValue"
                                editor.putString("user_name", igNameEdit.getText().toString());
                                // 提交修改
                                editor.apply();

                                startActivity(intent);
                                setResult(RESULT_OK, intent); // 设置结果
                                finish(); // 结束当前活动
                            }
                        });
                    }
                    break;


                }
                else { //返回用户原来的消息
                    String[] parts = message.split(" ");
                    if(!isFinishing()){
                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
                            @Override
                            public void run() {
                                //更新UI界面
                                igNameEdit.setText(parts[0]);
                                igGenderRr.setText(parts[1]);
                                igRegionn.setText(parts[2]);
                                brithday.setText(parts[3]);
                            }
                        });
                    }
                }


            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public class Worker implements Runnable {
        private String message;
        public Worker(String message) {
            this.message = message;
        }
        @Override
        public void run() {
            // 使用传递的消息

            out.println(message);

        }
    }

    //    //重写onDestroy()方法
    @Override
    protected void onDestroy() {
        super.onDestroy();
        try{

            if(socket!=null){
                socket.close();
                in.close();
                out.close();
            }

        }catch(IOException e){
            e.printStackTrace();

        }

    }
}
